package com.gameapplet.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

public class AESUtil {
        public static final AESUtil instance = new AESUtil();

        public static boolean initialized = false;

        /**
         * AES解密
         * @param
         * @return
         * @throws InvalidAlgorithmParameterException
         * @throws NoSuchProviderException
         */

        public byte[] decrypt(String encryptedData,String sessionKey,String iv) throws InvalidAlgorithmParameterException {
            initialize();
            try {
                byte[] content = Base64Util.decodeByte(encryptedData);
                // 加密秘钥
                byte[] keyByte = Base64Util.decodeByte(sessionKey);
                // 偏移量
                byte[] ivByte = Base64Util.decodeByte(iv);

                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                Key sKeySpec = new SecretKeySpec(keyByte, "AES");

                cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
                byte[] result = cipher.doFinal(content);//

                return result;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (Exception e) {
                //
                e.printStackTrace();
            }
            return null;
        }

        public static void initialize(){
            if (initialized) return;
            Security.addProvider(new BouncyCastleProvider());
            initialized = true;
        }
        //生成iv
        public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(iv));
            return params;
        }
    }
